<template>
	<div class="area-delay-chart">
		<div ref="chartRef" class="chart-container" style="width:100%;height:100%;">
			<div v-if="loading" class="chart-loading"><el-skeleton :rows="8" animated /></div>
			<div v-else-if="!hasValidData" class="chart-empty"><el-empty description="暂无数据" /></div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted, nextTick, computed } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
	data: { type: Object, default: null },
	loading: { type: Boolean, default: false }
});

const chartRef = ref<HTMLElement | null>(null);
let chartInstance: echarts.ECharts | null = null;
let isDestroyed = false;

// 检查是否有有效数据
const hasValidData = computed(() => {
	if (!props.data || typeof props.data !== 'object') return false;
	return Array.isArray(props.data.categories) && props.data.categories.length > 0 && 
		   Array.isArray(props.data.totalCounts) && props.data.totalCounts.length > 0 && 
		   Array.isArray(props.data.delayCounts) && props.data.delayCounts.length > 0 && 
		   Array.isArray(props.data.delayRates) && props.data.delayRates.length > 0;
});

// 初始化图表
const initChart = () => {
	if (isDestroyed || !chartRef.value) return;
	
	try {
		if (chartInstance) {
			chartInstance.dispose();
			chartInstance = null;
		}
		chartInstance = echarts.init(chartRef.value);
	} catch (error) {
		console.error('AreaDelayChart 初始化图表失败:', error);
	}
};

// 渲染图表
const renderChart = () => {
	if (isDestroyed || !chartRef.value || !chartInstance || !hasValidData.value) {
		return;
	}
	
	try {
		const option = {
			title: {
				text: '各区域延期情况',
				left: 'center',
				textStyle: { fontSize: 16, fontWeight: 'bold', color: '#303133' }
			},
			tooltip: {
				trigger: 'axis',
				axisPointer: { type: 'shadow' },
				formatter: (params: any) => {
					const dataIndex = params[0].dataIndex;
					return `
						<div style="padding: 8px;">
							<div style="font-weight: bold; margin-bottom: 8px;">${props.data.categories?.[dataIndex]}</div>
							<div style="color: #409eff;">总计划数: ${props.data.totalCounts?.[dataIndex]}</div>
							<div style="color: #f56c6c;">延期数量: ${props.data.delayCounts?.[dataIndex]}</div>
							<div style="color: #e6a23c;">延期率: ${props.data.delayRates?.[dataIndex]}%</div>
						</div>
					`;
				}
			},
			legend: {
				data: ['总计划数', '延期数量', '延期率'],
				top: 40,
				itemGap: 20
			},
			grid: { left: '3%', right: '4%', bottom: '8%', top: '20%', containLabel: true },
			xAxis: [{
				type: 'category',
				data: props.data.categories || [],
				axisTick: { alignWithLabel: true },
				axisLabel: { rotate: 0, interval: 0, fontSize: 12 }
			}],
			yAxis: [
				{ type: 'value', name: '数量', position: 'left', axisLabel: { formatter: '{value}' } },
				{ type: 'value', name: '延期率(%)', position: 'right', axisLabel: { formatter: '{value}%' } }
			],
			series: [
				{
					name: '总计划数',
					type: 'bar',
					yAxisIndex: 0,
					data: props.data.totalCounts || [],
					itemStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [ { offset: 0, color: '#409eff' }, { offset: 1, color: '#79bbff' } ]) },
					barWidth: '25%'
				},
				{
					name: '延期数量',
					type: 'bar',
					yAxisIndex: 0,
					data: props.data.delayCounts || [],
					itemStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [ { offset: 0, color: '#f56c6c' }, { offset: 1, color: '#f89898' } ]) },
					barWidth: '25%'
				},
				{
					name: '延期率',
					type: 'line',
					yAxisIndex: 1,
					data: props.data.delayRates || [],
					lineStyle: { color: '#e6a23c', width: 3 },
					itemStyle: { color: '#e6a23c' },
					symbol: 'circle',
					symbolSize: 8,
					smooth: true
				}
			],
			animation: true,
			animationDuration: 1000,
			animationEasing: 'cubicOut' as const
		};
		
		chartInstance.setOption(option, true);
		chartInstance.resize();
	} catch (error) {
		console.error('AreaDelayChart 渲染图表失败:', error);
	}
};

// 监听数据变化并渲染图表
watch(() => props.data, () => {
	if (isDestroyed || props.loading || !hasValidData.value) return;
	
	nextTick(() => {
		if (!chartInstance && chartRef.value) {
			initChart();
		}
		renderChart();
	});
}, { deep: true });

// 监听加载状态变化
watch(() => props.loading, (loading) => {
	if (isDestroyed) return;
	
	if (!loading && hasValidData.value) {
		nextTick(() => {
			if (!chartInstance && chartRef.value) {
				initChart();
			}
			renderChart();
		});
	}
});

onMounted(() => {
	nextTick(() => {
		if (chartRef.value && !isDestroyed) {
			initChart();
			
			const handleResize = () => {
				if (chartInstance && !isDestroyed) {
					chartInstance.resize();
				}
			};
			window.addEventListener('resize', handleResize);
			
			if (hasValidData.value && !props.loading) {
				renderChart();
			}
		}
	});
});

onUnmounted(() => {
	isDestroyed = true;
	if (chartInstance) {
		chartInstance.dispose();
		chartInstance = null;
	}
});
</script>

<style lang="scss" scoped>
.chart-container { 
	width: 100%; 
	height: 100%; 
	min-height: 344px; 
	position: relative; 
}

.chart-loading, .chart-empty { 
	position: absolute; 
	top: 0; 
	left: 0; 
	right: 0; 
	bottom: 0; 
	background: rgba(255,255,255,0.9); 
	display: flex; 
	align-items: center; 
	justify-content: center; 
	z-index: 10; 
	padding: 20px; 
}

@media (max-width: 768px) { 
	.chart-container { 
		min-height: 300px; 
	} 
}
</style>